const Controller=qguan("Controller")

/**
 * web端依赖
 */
@Controller("/lib")
export default  class LibCtrl{
    //用户登录
    @Controller("/find")
    find(req,res,url){
        res.setHeader("Content-Type", "application/x-javascript");
        res.setHeader("Content-Disposition", "attachment; filename="+url.query.name);
        res.setHeader("Access-Control-Allow-Origin", "*");
        try{
            //  this.userService.add();

            let code= Codes.getInstance().find(url.query.id);
            res.write(code)
            res.end();

        }catch (e) {
            res.write({
                message: '异常'
            })
            return;
        }

    }

    //用户登录
    @Controller("/save")
    save(req,res,url){
        try{
            let code=req.body.code;
            let id= Codes.getInstance().save(code)
            let json=JSON.stringify({                'id':  id            })
            //  this.userService.add();
            res.write(json)
            res.end();

        }catch (e) {
            res.write({
                message: '异常'
            })
            return;
        }

    }

}

class Codes{
    constructor(){
        this.code={}

    }
   static getInstance(){
        if (!Codes.instance){
            Codes.instance = new Codes();
        }
        return  Codes.instance;
    }
      find(id){
        let code=this.code[id];
        delete this.code[id];
        return code;
    }
       save(code){
        let id=Codes.uuid();
           this.code[id]=code;
        return id;
    }

    static uuid(){
        let s = [];
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        let uuid = s.join("");
        return uuid;
    }


}

